package fi.tuomio.helloscala
import java.net._
import java.io._

object DrunkenBot {

	val random = new java.util.Random()

	def main(args: Array[String]) {
		val ia = InetAddress.getByName("localhost")
		val socket = new Socket(ia, 12111)	  
		try {
			client(socket)
		} catch {case e:SocketException => {}}
		finally (socket.close())
	}  

	def client(socket:Socket) {
		val out = new OutputStreamWriter(socket.getOutputStream(), "ISO-8859-1")
		val in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ISO-8859-1"))
		var oldAction = ""
		in.readLine()
		write(out, "DrunkenBot"+socket.getLocalPort)
		do {
			var input = in.readLine
			var output = randomAction(input, oldAction)
			oldAction = output
			write(out, output)
			Thread.sleep(10)
		} while ( true )
	}

	def write(out: OutputStreamWriter, line:String) {
		out.write(line + "\n")
		out.flush
	}

	def randomAction(in:String, oldAction:String) : String = {
			val options = in split " "
			val directions = options(0) split ","
			if (random.nextBoolean) return randomAction()
			if ((directions.contains("r")) && random.nextBoolean) return "r"
			if ((directions.contains("l")) && random.nextBoolean) return "l"
			if (directions.contains("f")) return "f"
			if (directions.contains("r")) return "r"
			if (directions.contains("l")) return "l"
			"b"
	}

	def randomAction():String = {
			val actions = List("Harrrrr!!!", "BURP!!!", "I don't feel too good", "I'm off to O'Connells", "Hey, where do you think you are going, the goal is over there *points north*",
					"Who was that maude person anyway?")
					val i = randomPositiveInt(actions.length)
					actions(i)
	}

	def pickRandomDirection(in:Array[String]):String =
			in(random.nextInt(in.size))

	def randomPositiveInt(n: Int) = random.nextInt(n)
}
